﻿using DataAccess;
using DataAccess.Api;
using DataAccess.DAL;
using DataAccess.DTO;
using DataAccess.Models;
using DataAccess.ViewModel.Web;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Web.Controllers
{
    public class AgencyUserController : BaseController
    {
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public JsonResult GetAgencyUsers(AgentUserListVM vm)
        {
            AgencyUsersDAL userDAL = new AgencyUsersDAL();

            //string keyword = System.Web.HttpContext.Current.Request.Form["keyword"];
            if (vm.limit == 0) vm.limit = 20;
            if (vm.offset == 0) vm.offset = 1;
            if (vm.state == 0) vm.state = -1;
            //int limit = XYD.Common.Request.GetFormInt("limit", 5);
            //int offset = XYD.Common.Request.GetFormInt("offset", 1);
            //int state = XYD.Common.Request.GetFormInt("state", -1);
            //string aliid = XYD.Common.Request.GetFormString("aliid");
            //string oneagen = XYD.Common.Request.GetFormString("oneagen");
            //string twoagen = XYD.Common.Request.GetFormString("twoagen");

            string strWhere = " promoter_id=@promoter_id ";
            string orderbys = " add_data desc  ";

            if (vm.state != -1)
            {
                strWhere += " and state=@state";
            }
            if (!string.IsNullOrEmpty(vm.oneagen))
            {
                strWhere += " and superior=(select id  from [dbo].[AgencyUsers] where username =@oneagen) ";
            }
            if (!string.IsNullOrEmpty(vm.twoagen))
            {
                strWhere += " and onthe_superior=(select id  from [dbo].[AgencyUsers] where username =@twoagen) ";
            }
            if (!string.IsNullOrEmpty(vm.aliid))
            {
                strWhere += " and alimama_id=@aliid";
            }
            if (!string.IsNullOrEmpty(vm.keyword))
            {
                strWhere += string.Format(" and ( username like {0} or nickname like {0} or remark like {0} or wechat_pid like {0}  or qq_pid like {0} or site_pid like {0}    )", "@keyword");
            }
            int count = 0;

            var param = new { state = vm.state, oneagen = vm.oneagen, twoagen = vm.twoagen, aliid = vm.aliid, keyword = string.Format("%{0}%", vm.keyword), promoter_id=UserSession.user_id };

            // List<AgencyUsers> users = userDAL.ListPage(strWhere, orderbys, vm.limit,(vm.offset / vm.limit) + 1, param, out count);
            List<AgencyUsers> users = userDAL.ListPage(strWhere, orderbys, vm.limit, (vm.offset), param, out count);

            //int limit, int offset, int pageSize, int pageNumber

            Result result = new Result();
            result.State = true;
            result.Message = "查询成功";
            result.Datas = new PageData<AgencyUsers> { Total = count, Rows = users, PageIndex = vm.offset, PageSize = vm.limit };

            return Json(result);
        }

        public ActionResult EditAgencyUser(int id = 0)
        {
            AgencyUsersDAL userDAL = new AgencyUsersDAL();

            AgencyUsers user;
            if (id != 0)
            {
                user = userDAL.Get(id);
            }
            else
            {
                //设置默认值
                user = new AgencyUsers();
                user.permission = "";
                //启用
                user.state = 1;

                SysConfigDAL sysConfigDAL = new SysConfigDAL();
                SysConfig sysConfig = sysConfigDAL.GetSysConfig();
                if (sysConfig != null)
                {
                    //设置默认佣金比例
                    user.commission = sysConfig.rate;
                    user.superior_commission = sysConfig.rate_i;
                    user.onthe_superior_commission = sysConfig.rate_ii;



                }



            }
            /////////////////////////////////

            //联盟账号
            AlimamaDAL alimamaDAL = new AlimamaDAL();
            List<Alimama> alimamas = alimamaDAL.Get_Alimama_List(UserSession.user_id.ToString());
            List<SelectListItem> alimmSLI = new List<SelectListItem>();
            alimamas.ForEach(l =>
            {
                if (!string.IsNullOrEmpty(user.alimamaid) && user.alimamaid == l.alimamaid)
                {
                    alimmSLI.Add(new SelectListItem() { Text = l.username, Value = l.alimamaid, Selected = true });
                }
                else
                    alimmSLI.Add(new SelectListItem() { Text = l.username, Value = l.alimamaid });

            });
            ViewBag.Alimamas = alimmSLI;

            //代理列表
            List<AgencyUsers> users = new List<AgencyUsers>();
            users = userDAL.GetUsers(UserSession.user_id);
            ViewBag.Users = users;

            //上级
            AgencyUsers superior = new AgencyUsers();
            List<SelectListItem> superiorSLI = new List<SelectListItem>();
            superiorSLI.Add(new SelectListItem() { Text = "请选择", Value = "0" });
            List<SelectListItem> onthe_superiorSLI = new List<SelectListItem>();
            onthe_superiorSLI.Add(new SelectListItem() { Text = "请选择", Value = "0" });
            users.ForEach(l =>
            {
                if (user.superior != 0 && user.superior == l.id)
                {
                    //superior = userDAL.Get(user.superior);
                    superiorSLI.Add(new SelectListItem() { Text = l.username, Value = l.id.ToString(), Selected = true });
                }
                else
                    superiorSLI.Add(new SelectListItem() { Text = l.username, Value = l.id.ToString() });


                if (user.onthe_superior != 0 && user.onthe_superior == l.id)
                {
                    //superior = userDAL.Get(user.superior);
                    onthe_superiorSLI.Add(new SelectListItem() { Text = l.username, Value = l.id.ToString(), Selected = true });
                }
                else
                    onthe_superiorSLI.Add(new SelectListItem() { Text = l.username, Value = l.id.ToString() });
            });


            ViewBag.superior = superiorSLI;

            //上上级

            //AgencyUsers onthe_superior = new AgencyUsers();
            //if (user.onthe_superior != 0)
            //{
            //    onthe_superior = userDAL.Get(user.onthe_superior);
            //}

            ViewBag.onthe_superior = onthe_superiorSLI;




            return View(user);
        }

        [HttpPost]
        public JsonResult EditedAgencyUser(AgencyUsers model)
        {
            AgencyUsersDAL userDAL = new AgencyUsersDAL();

            AgencyUsers user = new AgencyUsers();

            if (model.id != 0)
            {
                user = userDAL.Get(model.id);
                user.state = (model.state);
                //user.username = obj.username.Value;
                user.password = XYD.Common.EncodeSecurity.EncryptString(model.password);
                user.nickname = model.nickname;
                user.tel = model.tel;
                user.remark = model.remark;


                user.alimamaid = model.alimamaid;
                //if (user.promotion == 0)
                {
                    user.superior = model.superior;
                }
                user.commission = (model.commission);
                user.superior_commission = (model.superior_commission);
                user.onthe_superior = model.onthe_superior;
                user.onthe_superior_commission = model.onthe_superior_commission;

                user.permission = string.IsNullOrEmpty(model.permission) ? "" : model.permission;

                if (user.superior == 0)
                    user.superior_commission = 0;
                if (user.onthe_superior == 0)
                    user.onthe_superior_commission = 0;


                bool boo = userDAL.Update(user);
                if (boo)
                {
                    var redisKey = RedisKey.AgencyUser(UserSession.user_id.ToString(), user.username);
                    if (!RedisHelper.Exist(redisKey))
                    {
                        RedisHelper.Single_Set_Itme<AgencyUsers>(redisKey, user);
                    }
                    else
                    {
                        RedisHelper.Single_Remove_Itme(redisKey);
                        RedisHelper.Single_Set_Itme<AgencyUsers>(redisKey, user);
                    }

                }

                return Json(new Result { State = boo, Message = boo ? "更新成功" : "更新失败" });
            }
            else
            {

                if (userDAL.Exist(model.username,UserSession.user_id.ToString()))
                {
                    return Json(new Result { State = false, Message = "添加失败，已存在相同账号" });
                }

                user.state = (model.state);
                user.username = model.username;
                user.password = XYD.Common.EncodeSecurity.EncryptString(model.password);
                user.nickname = model.nickname;
                user.tel = model.tel;
                user.remark = model.remark;

                user.superior = 0;
                user.add_data = DateTime.Now;
                user.promoter_id = UserSession.user_id;
                user.head_img = "";
                user.label = "";


                user.alimamaid = model.alimamaid;
                //if (user.promotion == 0)
                {
                    user.superior = model.superior;
                }
                user.commission = (model.commission);
                user.superior_commission = (model.superior_commission);
                user.onthe_superior = model.onthe_superior;
                user.onthe_superior_commission = model.onthe_superior_commission;

                user.permission = string.IsNullOrEmpty(model.permission) ? "" : model.permission;
                user.site_pid = "";
                user.qq_pid = "";
                user.wechat_pid = "";

                user.promotion = 1;
                if (string.IsNullOrEmpty(user.tel))
                    user.tel = "";

                if (string.IsNullOrEmpty(user.remark))
                    user.remark = "";

                user.site_adzoneid = "";
                user.wechat_adzoneid = "";
                user.qq_adzoneid = "";

                if (user.superior == 0)
                    user.superior_commission = 0;
                if (user.onthe_superior == 0)
                    user.onthe_superior_commission = 0;


                bool boo = userDAL.Insert(user);
                if (boo)
                { 
                    //写入Reids
                    var redisKey = RedisKey.AgencyUser(UserSession.user_id.ToString(), user.username);
                    if (!RedisHelper.Exist(redisKey))
                    {
                        //agencyUsers = new DataAccess.DAL.AgencyUsersDAL().Get(UserSession.user_id);
                        RedisHelper.Single_Set_Itme<AgencyUsers>(redisKey, user);
                    }
                    else
                    { 
                        //存在就有问题了 及时处理
                    }

                }

                return Json(new Result { State = boo, Message = boo ? "添加成功" : "添加失败" });
            }
        }



        #region 
        //[HttpGet]
        //public ActionResult RobotAgencyUser(int id)
        //{
        //    AgencyUsersDAL userDAL = new AgencyUsersDAL();
        //    AgencyUsers user = userDAL.Get(id);
        //    //if (user.send_interval == 0)
        //    //{
        //    //    user.send_interval = 600;
        //    //}
        //    return View(user);
        //}

        //[HttpPost]
        //public JsonResult RobotAgencyUser(FormCollection form)
        //{
        //    dynamic obj = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(XYD.Common.Utils.UrlDecode(Request.Form.ToString()));

        //    //{"id":"11","send_interval":"600","send_removal":"0","startHstr":"08,11,17","startMstr":"09,12,18","endHstr":"09,13,22","endMstr":"10,14,23"}

        //    AgencyUsersDAL userDAL = new AgencyUsersDAL();
        //    if (obj.id == null)
        //    {
        //        return Json(new Result { State = false, Message = "参数错误" });
        //    }

        //    if (int.Parse(obj.id.Value) == 1)
        //    {
        //        return Json(new Result { State = false, Message = "禁止修改" });
        //    }

        //    if (obj.startHstr == null || obj.startMstr == null || obj.endHstr == null || obj.endMstr == null)
        //    {
        //        return Json(new Result { State = false, Message = "配置参数错误" });
        //    }

        //    string[] startHArr = obj.startHstr.Value.ToString().Split(',');
        //    string[] startMArr = obj.startMstr.Value.ToString().Split(',');
        //    string[] endHArr = obj.endHstr.Value.ToString().Split(',');
        //    string[] endMArr = obj.endMstr.Value.ToString().Split(',');

        //    if (startHArr.Length != startMArr.Length || startHArr.Length != endHArr.Length || startHArr.Length != endMArr.Length)
        //    {
        //        return Json(new Result { State = false, Message = "配置参数错误" });
        //    }

        //    AgencyUsers user = userDAL.Get(int.Parse(obj.id.Value));

        //    if (user == null)
        //    {
        //        return Json(new Result { State = false, Message = "账号不存在" });
        //    }
        //    if (user.promotion == 0)
        //    {
        //        return Json(new Result { State = false, Message = "账号未开启代理" });
        //    }

        //    //  user.send_interval = int.Parse(obj.send_interval.Value);
        //    //  user.send_removal = int.Parse(obj.send_removal.Value);

        //    //stage11 stage12 stage13 stage14
        //    //stage21 stage22 stage23 stage24
        //    //stage31 stage32 stage33 stage34   
        //    //["09:00-12:00","13:00-16:00","18:00-23:00"]

        //    List<string> stages = new List<string>();

        //    for (int i = 0; i < startHArr.Length; i++)
        //    {
        //        stages.Add(string.Format("{0}:{1}-{2}:{3}", startHArr[i], startMArr[i], endHArr[i], endMArr[i]));
        //    }

        //    //  user.send_stage = XYD.Common.JsonHelper.SerializerJson<List<string>>(stages);

        //    bool boo = userDAL.Update(user);

        //    return Json(new Result { State = boo, Message = boo ? "设置成功" : "设置失败" });
        //}
        
        #endregion

        /// <summary>
        /// 更新pid
        /// </summary>
        /// <param name="accountName"></param>
        /// <param name="mmId"></param>
        /// <returns></returns>

        public JsonResult UpdatePid(string accountName )
        {

            //string robotApi = ConfigurationManager.AppSettings["robotApi"]; 

            //string apiUrl =robotApi+ "/V2/TK/SelfAdzoneCreate";
            Result res = new Result() { State = false, Message = "请求错误" };
            //{state:1,msg:"", "data":[{"adzoneId":"112072774","name":"qq_pzz1001","pid":"mm_122618678_30248620_112072774","type":"qq"},{"adzoneId":"112082343","name":"wx_pzz1001","pid":"mm_122618678_30264446_112082343","type":"wx"},{"adzoneId":"112076768","name":"wz_pzz1001","pid":"mm_122618678_30272265_112076768","type":"wz"}],"pvid":null}
            if (!string.IsNullOrEmpty(accountName) )
            {
                AgencyUsersDAL dal = new AgencyUsersDAL();
                var model = dal.Get(accountName,UserSession.user_id);
                if (model != null)
                {


                    if (string.IsNullOrEmpty(model.qq_pid) || string.IsNullOrEmpty(model.wechat_pid) || string.IsNullOrEmpty(model.site_pid))
                    {

                        if (string.IsNullOrEmpty(model.alimamaid))
                        {
                            res.State = false;
                            res.Message = "请先绑定联盟账号";
                            return Json(res, JsonRequestBehavior.AllowGet);
                        }

                        //var param = string.Format("?account={0}&username={1}", model.alimamaid, model.username);

                        //var response = XYD.Common.Utils.GetHttpWebResponse(apiUrl + param);
                        //调取机器人api 更新pid
                        var response = new RobotApiHelper().UpdatePid(model.alimamaid, model.username);
                        // var response = "{state:1,msg:\"ok\", \"data\":[{\"adzoneId\":\"112084570\",\"name\":\"qq_pzz1001\",\"pid\":\"mm_122618678_30248620_112084570\",\"type\":\"qq\"},{\"adzoneId\":\"112080862\",\"name\":\"wx_pzz1001\",\"pid\":\"mm_122618678_30264446_112080862\",\"type\":\"wx\"},{\"adzoneId\":\"112094139\",\"name\":\"wz_pzz1001\",\"pid\":\"mm_122618678_30272265_112094139\",\"type\":\"wz\"}],\"pvid\":null}";
                        var obj = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(XYD.Common.Utils.UrlDecode(response));
                        if (obj.state == 1)
                        {
                            var data = obj.data;
                            if (data != null)
                            {
                                foreach (var item in data)
                                {
                                    switch ((string)item.type)
                                    {
                                        case "wx":
                                            model.wechat_pid = item.pid;
                                            model.wechat_adzoneid = item.adzoneId;
                                            break;
                                        case "wz":
                                            model.site_pid = item.pid;
                                            model.site_adzoneid = item.adzoneId;
                                            break;
                                        case "qq":
                                            model.qq_pid = item.pid;
                                            model.qq_adzoneid = item.adzoneId;
                                            break;
                                    }
                                }
                                if (dal.Update(model))
                                {
                                    RedisHelper.Single_Remove_Itme(RedisKey.AgencyUser(model.promoter_id.ToString(), model.username));

                                    res.State = true;
                                    res.Message = "更新pid 成功";
                                }
                            }
                        }
                        else
                        {
                            res.Message = obj.msg;
                        }
                    }
                    else
                    {
                        res.Message = "pid已经存在";
                    }
                }
                else
                {
                    res.Message = "用户不存在";
                }

            }
            return Json(res, JsonRequestBehavior.AllowGet);

        }

    }
}